#https://blog.csdn.net/zhuisui_woxin/article/details/84400439
import cv2
import os
import Mahjong
import FlannMatch
import VideoStream

#import DetectCardsLib
from readconfig import ReadConfig
from ApiServer import HttpServer
from threading import Thread


path = os.path.dirname(os.path.abspath(__file__))
train_ranks = Mahjong.load_ranks( path + '/mahjong/')
def OpencvDetect(image):



    # Pre-process camera image (gray, blur, and threshold it)
    pre_proc = Mahjong.preprocess_image(image)

    # Find and sort the contours of all cards in the image (query cards)
    cnts_sort, cnt_is_card = Mahjong.find_cards(pre_proc)
    if len(cnts_sort) != 0:

        # Initialize a new "cards" list to assign the card objects.
        # k indexes the newly made array of cards.
        cards = []
        k = 0

        # For each contour detected:
        for i in range(len(cnts_sort)):
            if (cnt_is_card[i] == 1):
                cards.append(Mahjong.preprocess_card(cnts_sort[i],image))
                # Find the best rank and suit match for the card.
                cards[k].best_rank_match,cards[k].rank_diff = Mahjong.match_card(cards[k],train_ranks)
                # Draw center point and match result on the image.
                image = Mahjong.draw_results(image, cards[k])
                k = k + 1
        if (len(cards) != 0):
            temp_cnts = []
            for i in range(len(cards)):
                print(cards[i].best_rank_match+"=="+str(cards[i].rank_diff))
                print('best_rank:{}=best_x:{}=best_y:{}'.format(cards[i].best_rank_match,int(cards[i].center[0]),int(cards[i].center[1])))
                temp_cnts.append(cards[i].contour)
        cv2.drawContours(image,temp_cnts, -1, (255,0,0), 2)

if __name__ == '__main__':
    h_image=cv2.imread("4bing_7.jpg")
    # 找和排序轮廓
    OpencvDetect(h_image)
    print('Press "c" to continue.')
    key = cv2.waitKey(0) & 0xFF
    if key == ord('c'):
        pass
    # Close all windows and close the PiCamera video stream.
    cv2.destroyAllWindows()
    #videostream.stop()
